<?php
/**
 * @author ykm 2016/6/3
 * @describe 天猫售后数据转换
 */

class erpapi_shop_matrix_tmall_response_aftersalev2 extends erpapi_shop_response_aftersalev2 {

    protected function _formatAddParams($params) {
        if (($params['spider_type'] == 'tm_refund') || ($params['spider_type'] != 'tm_refund_i')) {
            $this->__apilog['result']['msg'] = '天猫售后老接口数据，不接受';
            return array();
        }
        $sdf = parent::_formatAddParams($params);
        $change_conf = app::get('ome')->getConf('shop.tmallchange.config.'.$this->__channelObj->channel['shop_id']);
        if ($change_conf){
            //格式化天猫换货数据
            //$change_flag = $this->_tranChange($params);
        }


        $item = current($sdf['refund_item_list']['return_item']);
        if($change_flag){
            $sdf['change_order_id'] = $change_flag['change_order_id'];
            $params['oid'] = '';
            $sdf['memo'] = '换货订单转换生成,原订单号:'.$params['tid'];
            $this->_tranChangeItems($sdf);
        }

        if($params['tag_list']) {
            $tagList = json_decode($params['tag_list'], true);
            $tagList = serialize($tagList);
        }

        //识别如果是已完成的售后，转成退款单更新的逻辑
        if($params['refund_type'] == 'return' && $params['status'] == 'success'){
            $refundOriginalObj = app::get('ome')->model('return_product');
            $refundOriginalInfo = $refundOriginalObj->getList('return_id', array('return_bn'=>$sdf['refund_bn'],'status' =>'4') , 0 , 1);
            if($refundOriginalInfo){
                $refundApplyObj = app::get('ome')->model('refund_apply');
                $refundApplyInfo = $refundApplyObj->getList('refund_apply_bn', array('return_id'=>$refundOriginalInfo[0]['return_id'],'status' =>array('0','1','2','5','6')) , 0 , 1);
                if($refundApplyInfo){
                    $sdf['refund_bn'] = $refundApplyInfo[0]['refund_apply_bn'];
                    $sdf['tmall_has_finished_return_product'] = true;
                }
            }
        }

        $tmallSdf = array(
            'oid'               => $params['oid'] ? $params['oid'] : $item['oid'],
            'tmall_refund_type' => $params['refund_type'],
            'refund_phase'      => $params['refund_phase'] ? $params['refund_phase'] : $item['refund_phase'],
            'cs_status'         => $params['cs_status'],
            'advance_status'    => $params['advance_status'],
            'split_taobao_fee'  => $params['split_taobao_fee'],
            'split_seller_fee'  => $params['split_seller_fee'],
            'total_fee'         => $params['total_fee'],
            'seller_nick'       => $params['seller_nick'],
            'good_status'       => $params['good_status'],
            'current_phase_timeout'=>strtotime($params['current_phase_timeout']),
            'ship_addr'         => $params['receiver_address'],
            'tag_list'          => $tagList ? $tagList : '',
            'address'           => $params['address'] ? $params['address'] : '',
            'shipping_type'   => $params['shipping_type'],
            'buyer_nick'      => $params['buyer_nick'],
            'has_good_return' => $params['has_good_return'],
            'good_return_time'=> $params['good_return_time'],
            'refund_type'     => $params['refund_type'],
            'refund_version'  => $params['refund_version'],
            'alipay_no'       => $params['payment_id'],
            'trade_status'      =>$params['trade_status'],
            'bill_type'       => $params['bill_type'],
            't_ready'         =>$sdf['created'],
            't_sent'          =>$sdf['modified'],
            't_received'      =>'',
            'attribute'         =>  $params['attribute'],
        );
        return array_merge($sdf, $tmallSdf);
    }

    protected function _getAddType($sdf) {
        if ($sdf['refund_type'] == 'return') {
            if (in_array($sdf['order']['ship_status'],array('0'))) {
                #退款单
                return 'refund';
            }elseif(in_array($sdf['order']['ship_status'],array('3','4')) && $sdf['tmall_has_finished_return_product']){
                #退款单
                return 'refund';
            }else{
                #退货申请单
                return 'returnProduct';
            }
        }elseif($sdf['refund_type'] == 'reship'){
            #退货单
            return 'reship';
        }else{
            #退款单
            return 'refund';
        }
    }

    protected function _formatAddItemList($sdf, $convert = array()) {
        if($sdf['refund_type'] == 'reship') {
            return array();
        }
        $convert = array(
            'sdf_field'=>'oid',
            'order_field'=>'oid',
            'default_field'=>'outer_id'
        );
        return parent::_formatAddItemList($sdf, $convert);
    }

    protected function _calculateAddPrice($refundItems, $sdf) {
        $items = parent::_calculateAddPrice($refundItems, $sdf);
        $allNum = 0;
        foreach($items as $val) {
            $allNum += $val['num'];
        }
        $refundFee = $sdf['refund_fee'] ? $sdf['refund_fee'] : $sdf['return_product']['money'];
        $averagePrice = sprintf('%.2f', $refundFee / $allNum);
        foreach($items as &$val) {
            $val['price'] = $averagePrice;
        }
        return $items;
    }

    protected function _refundApplyAdditional($sdf) {
        $ret = array(
            'model' => 'refund_apply_tmall',
            'data' => array(
                'shop_id'           => $sdf['shop_id'],
                'shipping_type'     => $sdf['shipping_type'],
                'cs_status'         => $sdf['cs_status'],
                'advance_status'    => $sdf['advance_status'],
                'split_taobao_fee'  => $sdf['split_taobao_fee'],
                'split_seller_fee'  => $sdf['split_seller_fee'],
                'total_fee'         => $sdf['total_fee'],
                'buyer_nick'        => $sdf['buyer_nick'],
                'seller_nick'       => $sdf['seller_nick'],
                'good_status'       => $sdf['good_status'],
                'has_good_return'   => $sdf['has_good_return'],
                'good_return_time'  => $sdf['good_return_time'],
                'oid'               => $sdf['oid'],
                'refund_version'    => $sdf['refund_version'],
                'bill_type'         => $sdf['bill_type'],
                'outer_lastmodify'  => $sdf['modified'],
                'alipay_no'         => $sdf['alipay_no'],
                'current_phase_timeout'=>$sdf['current_phase_timeout'],
                'refund_type'       => $sdf['tmall_refund_type'] ? $sdf['tmall_refund_type'] : '',
                'refund_phase'      => $sdf['refund_phase'] ? $sdf['refund_phase'] : '',
                'tag_list'          => $sdf['tag_list'],
                'refund_fee'         => $sdf['refund_fee'],
            )
        );
        return $ret;
    }

    protected function _refundAddSdf($sdf){
        $sdf['shop_type'] = 'tmall';
        if(self::$refund_status[strtoupper($sdf['status'])] != '4') {
            $sdf['refund_type'] = 'apply';
        }
        $sdf = parent::_refundAddSdf($sdf);
        /*
        if($sdf['refund_apply']) {
            $oRefundTmall = app::get('ome')->model('refund_apply_tmall');
            $refundTmallData = $oRefundTmall->getList('refund_version', array('apply_id'=>$sdf['refund_apply']['apply_id'],'shop_id'=>$sdf['shop_id']), 0, 1);
            if ($sdf['refund_version'] > $refundTmallData[0]['refund_version']) {
                $sdf['refund_version_change'] = true;
                $sdf['table_additional'] = $this->_refundApplyAdditional($sdf);
            } else {
                $sdf['refund_version_change'] = false;
            }
        }
        */
        return $sdf;
    }

    protected function _returnProductAdditional($sdf) {
        $ret = array(
            'model' => 'return_product_tmall',
            'data' => array(
                'shop_id'         => $sdf['shop_id'],
                'shipping_type'   => $sdf['shipping_type'],
                'cs_status'       => $sdf['cs_status'],
                'advance_status'  => $sdf['advance_status'],
                'split_taobao_fee'=> $sdf['split_taobao_fee'],
                'split_seller_fee'=> $sdf['split_seller_fee'],
                'total_fee'       => $sdf['total_fee'],
                'buyer_nick'      => $sdf['buyer_nick'],
                'seller_nick'     => $sdf['seller_nick'],
                'good_status'     => $sdf['good_status'],
                'has_good_return' => $sdf['has_good_return'],
                'good_return_time'=> $sdf['good_return_time'],
                'refund_type'     => $sdf['refund_type'],
                'refund_phase'    => $sdf['refund_phase'],
                'refund_version'  => $sdf['refund_version'],
                'alipay_no'       => $sdf['alipay_no'],
                'trade_status'    => $sdf['trade_status'],
                'oid'             => $sdf['oid'],
                'bill_type'       => $sdf['bill_type'],
                'current_phase_timeout'=>$sdf['current_phase_timeout'],
                'tag_list'        => $sdf['tag_list'],
                'address'         => $sdf['address'],
                'refund_fee'         => $sdf['refund_fee'],
            )
        );
        return $ret;
    }

    protected function _returnProductAddSdf($sdf) {
        $sdf['shop_type'] = 'tmall';
        $sdf = parent::_returnProductAddSdf($sdf);
        if(!$sdf) {
            return false;
        }
        $sdf['choose_type_flag'] = 0;
        if($sdf['return_product']) {
            $oRefundTmall = app::get('ome')->model('return_product_tmall');
            $refundTmallData = $oRefundTmall->getList('refund_version', array('return_id'=>$sdf['return_product']['return_id'],'shop_id'=>$sdf['shop_id']), 0, 1);
            if ($sdf['refund_version'] > $refundTmallData[0]['refund_version']) {
                $sdf['refund_version_change'] = true;
            } else {
                $sdf['refund_version_change'] = false;
            }
        }
        $sdf['table_additional'] = $this->_returnProductAdditional($sdf);
        return $sdf;
    }

    /*
    * 判断是否已产生换货后退货订单
    *
    *
    */
    protected function _tranChange($sdf){
        $oid = $sdf['oid'];
        $tid = $sdf['tid'];
        $db = kernel::database();
        $sql = "SELECT r.change_order_id FROM sdb_ome_return_product_tmall as t LEFT JOIN sdb_ome_reship as r ON t.return_id=r.return_id WHERE t.oid='".$oid."' AND r.is_check not in('5','9') AND r.return_type='change'";
        $reship_detail = $db->selectrow($sql);
        if($reship_detail){
            $sql = "SELECT o.order_id as change_order_id FROM sdb_ome_orders as o  WHERE o.relate_order_bn='".$tid."' AND o.order_id=".$reship_detail['change_order_id'];
            $order_detail = $db->selectrow($sql);
            return $order_detail;
        }

    }


    protected function _tranChangeItems(&$sdf){
        $order_id = $sdf['change_order_id'];
        $orderObj = app::get('ome')->model('orders');
        $itemObj = app::get('ome')->model('order_items');
        if ($order_id>0){
            $order_detail = $orderObj->dump($order_id,"order_id,order_bn",array("order_objects"=>array("*",array("order_items"=>array('*')))));

        if($order_detail){
            $sdf['tid']  =$sdf['order_bn']   =   $order_detail['order_bn'];
            $order_object = current($order_detail['order_objects']);
            $return_item = $sdf['refund_item_list']['return_item'];
            $return_item    =    current($return_item);
            $item_list = array();
            //判断是否捆绑
            $obj_type = $order_object['obj_type'];
            $radio = $return_item['num']/$order_object['quantity'];

                foreach($order_object['order_items'] as $ov){
                    if($ov['delete'] == 'false'){

                        $item_list[] = array(
                            'product_id' => $ov['product_id'],
                            'bn'         => $ov['bn'],
                            'name'       => $ov['name'],
                            'num'        => $obj_type == 'pkg' ? (int)($radio * $ov['quantity']) : $return_item['num'],
                            'price'      => $obj_type == 'pkg' ? $ov['price'] : $return_item['price'],
                            'sendNum'   =>  $ov['sendnum'],
                            'op_id'     => '888888',
                        );

                    }

                }

                $sdf['refund_item_list'] = $item_list;

            }
        }

    }
}
